package com.fingard.dsp.bank.directbank.bozz11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;

public class BOZZ11ScheduleTask extends BOZZ11Base implements IScheduleTask {
    public static boolean isRunded = false;

    @Override
    public void execTask(TaskTimerSet timerSet) {
        try {
            if (timerSet.taskNameList.toLowerCase().contains("pushdata")) {
                pushData();
            }
        } catch (Exception ex) {
            this.WriteBankLogLn(ex);
        }
    }

    public void pushData() throws IOException {
        try {
            // 获取日切时间判断是否可以执行定时任务
            Date tmpDateNow = new Date();
            String dayCutTime = getBankConfig().getValueAsString("dayCutTime");
            if (StringHelper.hasAnyChar(dayCutTime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(tmpDateNow);

                Calendar endCalendar = Calendar.getInstance();
                String time = String.format("%4s", dayCutTime.replace(":", "")).replace(" ", "0");
                endCalendar.setTime(Format.Time6Format.parse(time + "00"));
                endCalendar.add(Calendar.MINUTE, 15);
                String endDateTime = endCalendar.get(Calendar.HOUR_OF_DAY) + ":" + String.format("%2s",endCalendar.get(Calendar.MINUTE)).replace(" ", "0");

                int tmpDayCutTime = Integer.parseInt(dayCutTime.replace(":", ""));
                WriteBankLogLn("日切时间范围:[" + dayCutTime + "~" + endDateTime + "].");
                int tmpTimeNow = calendar.get(Calendar.HOUR_OF_DAY) * 100 + calendar.get(Calendar.MINUTE);
                String tmpTimeEnd = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
                WriteBankLogLn("当前时间:[" + tmpTimeEnd + "].");
                if (tmpTimeNow >= tmpDayCutTime && (tmpTimeNow < tmpDayCutTime + 1) && !isRunded) {
                    // 开始执行文件上传任务
                    WriteBankLogLn("开始执行文件上传任务...");
                    String tmpPaySendDate = Format.Date8Format.format(calendar.getTime());

                    String[] cdFlags = new String[]{"01","02"};
                    for(String cdFlag : cdFlags) {
                        //保险公司类别+"_"+"001"+"_"+日期+"_01.txt"
                        String tmpUploadFileName = bankFront.corpNo + "_001_" + tmpPaySendDate + "_" + cdFlag + ".txt";
                        String tmpLocalMarkPath = getTempFileDirectory(calendar.getTime()) + File.separator + tmpUploadFileName;
                        WriteBankLogLn("待上传本机批次明细文件路径:" + tmpLocalMarkPath);
                        File tmpLocalMarkFile = new File(tmpLocalMarkPath);
                        if (tmpLocalMarkFile.exists()) {
                            String detailFileMsg = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                            WriteBankLogLn("开始读取批次明细文件内容，用于读取明细总笔数总金额拼接到汇总文件中,当日批次明细文件内容:\r\n" + detailFileMsg);

                            int totalNum = 0;
                            double totalAmt = 0;

                            StringReader tmpStrReader = new StringReader(detailFileMsg);
                            BufferedReader tmpBuferReader = new BufferedReader(tmpStrReader);
                            while (true) {
                                String eachline = tmpBuferReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                totalNum++;
                                totalAmt += Double.parseDouble(eachline.split("\\|")[2]);
                            }

                            String tmpTotalNum = leftFill(String.valueOf(totalNum), 4);
                            String tmpTotalAmt = leftFill(String.valueOf(totalAmt), 16);
                            String contractNo = leftFill(bankFront.protocolNo, 10);
                            String totalContent = MessageFormat.format("INSURE|{0}|{1}|{2}|{3}|{4}|\n", bankFront.corpNo, tmpPaySendDate, tmpTotalNum, tmpTotalAmt, contractNo);
                            WriteBankLogLn("当日汇总文件内容:" + totalContent);
                            FileHelper.writeFile(tmpLocalMarkPath, totalContent+detailFileMsg, getCharset());

                            // 上送FTP服务器
                            FtpSet ftpSet = bankFront.getFtpSet("bat");
                            MixFtp mixFtp = new MixFtp(ftpSet);
                            FtpReceiver ftpReceiver = mixFtp.uploadFileToDir(tmpLocalMarkPath, ftpSet.upDir, tmpUploadFileName);
                            if (!ftpReceiver.isCompleted) {
                                WriteBankLogLn("本机批次代收付文件上传失败，原因:\r\n" + ftpReceiver.connMsg);
                            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                                WriteBankLogLn("本机批次代收付文件上传失败，原因:\r\n" + ConnState.FAIL);
                            } else {
                                WriteBankLogLn("批次批次代收付文件上传成功...\r\n");
                                isRunded = true;
                            }
                        } else {
                            WriteBankLogLn("本机文件:[" + tmpLocalMarkPath + "]不存在,本日无交易，无法执行文件上传任务!");
                        }
                    }
                } else {
                    int tmpSpan = tmpDayCutTime - tmpTimeNow;
                    if (tmpSpan > 0) {
                        WriteBankLogLn("定时将于" + (tmpSpan / 60) + "小时后开始执行文件上传任务!");
                    } else {
                        WriteBankLogLn("定时将于" + (tmpSpan / 60 + 24) + "小时后开始执行文件上传任务!");
                    }
                }
            } else {
                WriteBankLogLn("配置文件缺失:'dayCutTime'配置节点，不进行文件上传,请及时更新配置文件!");
            }
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }
    }
}